<template>
    <view class="daub">
        <view class="daub-upload">
            <view v-if="!daubImage" class="work-btn-style daub-upload-btn" @click="selectedFileData">上传空间图片</view>

            <view v-else class="daub-contianer">
                <!-- <view  class="daub-contianer"> -->
                <!-- <image class="daub-bg" :src="daubImage" mode="aspectFit"></image> -->
                <movable-area class="daub-area">
                    <movable-view class="daub-view" direction="all" :animation="false" out-of-bounds
                        :scale-value="scaleValue" :scale-min="0.8" :scale-max="4" @scale="scale" :disabled="disabled"
                        :scale="!disabled">
                        <image class="daub-bg" :src="daubImage" mode="aspectFit"></image>
                        <!-- <canvas id="myCanvas" class="daub-canvas" ref="canvas"></canvas> -->
                    </movable-view>
                </movable-area>
            </view>

        </view>
        <view class="daub-btn-group">

            <view class="daub-btn-item">
                <view class="daub-btn-icon">
                    <image src="@/static/images/fanhui.png" class="daub-btn-icon-img" />
                </view>
            </view>
            <view class="daub-btn-item" @click="scaleValue = 1">
                <view class="daub-btn-icon">
                    <image src="@/static/images/shuaxin.png" class="daub-btn-icon-img" />
                </view>
            </view>
            <view class="daub-btn-gap"></view>
            <view class="daub-btn-item">
                <view class="daub-btn-icon" :class="{ actived: isBrush }" @click="changeTool('brush')">
                    <image v-if="!isBrush" src="@/static/images/tumo.png" class="daub-btn-icon-img" />
                    <image v-else src="@/static/images/tumo-actived.png" class="daub-btn-icon-img" />
                </view>
                <view class="daub-btn-text">涂抹</view>
            </view>
            <view class="daub-btn-item">
                <view class="daub-btn-icon" :class="{ actived: isEraser }" @click="changeTool('eraser')">
                    <image v-if="!isEraser" src="@/static/images/clear.png" class="daub-btn-icon-img" />
                    <image v-else src="@/static/images/clear-actived.png" class="daub-btn-icon-img" />
                </view>
                <view class="daub-btn-text">橡皮擦</view>
            </view>
            <view class="daub-btn-item">
                <view class="daub-btn-icon" :class="{ actived: isMove }" @click="changeTool('move')">
                    <image v-if="!isMove" src="@/static/images/move.png" class="daub-btn-icon-img" />
                    <image v-else src="@/static/images/move-actived.png" class="daub-btn-icon-img" />
                </view>
                <view class="daub-btn-text">移动</view>
            </view>
        </view>
        <view class="prompt">
            <view class="title">重绘描述</view>
            <textarea :maxlength="-1" class="text" v-model="prompt" placeholder="描述一下希望将涂抹区域变成什么" />
        </view>

        <!-- 控制器 -->
        <view class="controller">
            <view class="work-btn-style btn" :class="{ disabled: !daubImage }" @click="daubImg">
                <text class="btn-text">点击生成</text>
                <text class="btn-price">（本次消耗{{ cost }}点积分）</text>
            </view>
        </view>
    </view>

</template>

<script setup>
import {
    ref
} from 'vue';

import {
    apiGetCostCheck
} from '@/api/accountApi.js'
import {
    apiDrawInpaint,
    BASE_URL
} from '@/api/defaultApi.js'

// pinia
import {
    storeToRefs
} from 'pinia'
import {
    useUserStore
} from "@/stores/useUserStore.js"

// 获取pinia的数据
const userStore = useUserStore()
const {
    token
} = storeToRefs(userStore)


const canvasId = 'myCanvas';
const ctx = ref(null);
let isDrawing = ref(false);
let lastPosition = ref({ x: 0, y: 0 });

const daubImage = ref('');              // 需要涂抹底图

const sketch_image = ref('')            // 绘制结果base64地址
const isMove = ref(false);            // 是否为移动工具
const isBrush = ref(false);            // 是否为画笔
const isEraser = ref(false);            // 是否为橡皮擦

const prompt = ref('')                  // 重绘描述
const cost = ref(0)                    // 费用

const scaleValue = ref(1)              //放大缩小倍数
const disabled = ref(true)            //是否禁用












//上传图片
const selectedFileData = () => {
    // 判断是否已获得相册授权
    // #ifdef MP-WEIXIN
    uni.authorize({
        scope: 'scope.writePhotosAlbum',
        success() {
            uni.chooseMedia({
                count: 1, // 默认9
                mediaType: ['image'],
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    let tempFileImg = ''

                    tempFileImg = res.tempFiles[0].tempFilePath
                    daubImage.value = tempFileImg
                },
                fail: function (err) {
                    uni.showToast({
                        title: "图片上传失败",
                        icon: "none",
                    })
                }
            })
        },
        fail() {
            // 未获得授权，提示用户前往设置页面授权
            uni.showModal({
                title: '提示',
                content: '您未授权访问相册，请前往设置页面授权',
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        // 跳转到应用设置页面
                        uni.openSetting({
                            success: function (res) {
                                if (res.authSetting['scope.writePhotosAlbum']) {
                                    // 用户已开启授权，可以再次尝试选择图片
                                    uni.chooseMedia({
                                        count: 1,
                                        sourceType: ['album', 'camera'],
                                        success: function (res) {
                                            let tempFileImg = ''
                                            // #ifdef H5
                                            tempFileImg = res.tempFilePaths[0]
                                            daubImage.value = tempFileImg
                                            // #endif

                                            // #ifndef H5
                                            tempFileImg = res.tempFiles[0].tempFilePath
                                            daubImage.value = tempFileImg
                                            // #endif
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
    });
    // #endif


    // #ifdef H5
    uni.chooseImage({
        count: 1, // 默认9
        sourceType: ['camera', 'album'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            let tempFileImg = ''
            tempFileImg = res.tempFilePaths[0]
            daubImage.value = tempFileImg

            console.log(daubImage.value);
        },
        fail: function (err) {
            uni.showToast({
                title: "图片上传失败",
                icon: "none",
            })
        }
    })
    // #endif
}

// 放大缩小
const scale = (e) => {
    scaleValue.value = e.detail.scale
}

// 切换工具
const changeTool = (tool) => {
    if (tool == 'move') {
        isMove.value = true
        isBrush.value = false
        isEraser.value = false
        disabled.value = false
        console.log('移动');
    } else if (tool == 'brush') {
        isMove.value = false
        isBrush.value = true
        isEraser.value = false
        disabled.value = true
        console.log('涂抹');
    } else if (tool == 'eraser') {
        isMove.value = false
        isBrush.value = false
        isEraser.value = true
        disabled.value = true
        console.log('橡皮擦');
    }
}

// 查询费用
const getCostCheck = async () => {
    let res = await apiGetCostCheck({
        kind: 3,
        mode: '无'
    })
    cost.value = res.data
}

// 生成
const daubImg = async () => {
    if (!daubImage.value) {
        return
    }

    sketch_image.value = ''





    uni.uploadFile({
        url: BASE_URL + '/inpaint/draw_inpaint',
        filePath: daubImage.value,
        name: 'filedata',
        header: {
            Authorization: 'bearer ' + token.value,
        },
        formData: {
            'sketch_image': sketch_image.value,
            'prompt': prompt.value
        },
        success(res) {

            const data = JSON.parse(res.data).data

            if (res.statusCode === 401) {
                uni.showToast({
                    title: "请登录后进行操作",
                    icon: "none",
                    success: () => {
                        setTimeout(() => {
                            uni.navigateTo({
                                url: '/pages/login/login'
                            })
                        }, 500)
                    }
                })
                return
            }
            if (res.statusCode === 500) {
                uni.showToast({
                    title: data.msg,
                    icon: "none",
                    showCancel: false,
                    confirmColor: '#000',
                    duration: 3000
                })
                return
            }


            let form = {
                'filedata': daubImage.value,
                'sketch_image': encodeURIComponent(sketch_image.value),
                'prompt': prompt.value,
                'cost': cost.value
            }



            if (JSON.parse(res.data).code === 0) {

                sketch_image.value = ''

                //取消画板的所有涂鸦

                uni.navigateTo({
                    url: '/pages/daubInfo/daubInfo?id=' + data + '&formData=' + JSON
                        .stringify(form)
                })
            }
        }
    })


}



getCostCheck()
</script>

<style lang="scss" scoped>
.daub {
    padding-top: 64rpx;

    .daub-upload {
        width: 686rpx;
        height: 514rpx;
        border: 2rpx dashed #333333;
        margin: 0 auto;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;

        .daub-contianer {
            width: 100%;
            height: 100%;

            .daub-area {
                width: 100%;
                height: 100%;

                .daub-view {
                    width: 100%;
                    height: 100%;

                    #myCanvas {
                        width: 100%;
                        height: 100%;
                        background: red;
                    }
                }
            }
        }

        .daub-upload-btn {
            width: 320rpx;
            height: 96rpx;
            border-radius: 48rpx;
            font-size: 30rpx;
            color: #000;
            margin: 0 auto;
        }
    }

    .daub-btn-group {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 56rpx;
        margin-top: 20rpx;

        .daub-btn-item {

            height: 100%;
            margin: 0 20rpx;
            display: flex;
            position: relative;

            .daub-btn-icon {
                width: 56rpx;
                height: 100%;
                background: #333333;
                border-radius: 10rpx;

                .daub-btn-icon-img,
                .daub-btn-icon-img-actived {
                    width: 100%;
                    height: 100%;
                    padding: 8rpx;
                    box-sizing: border-box;
                }

                &.actived {
                    background: #ffcb30
                }
            }

            .daub-btn-text {
                font-size: 20rpx;
                font-weight: 500;
                color: #ffffff;
                margin-left: 16rpx;
                line-height: 56rpx;
            }
        }

        .daub-btn-gap {
            width: 4rpx;
            height: 40rpx;
            background: #333333;
            margin: 0 20rpx;
        }
    }

    .prompt {
        margin: 64rpx auto 0;
        width: 686rpx;

        .title {
            width: 100%;
            height: 50rpx;
            line-height: 50rpx;
            font-size: 24rpx;
            font-weight: 500;
            color: #ffffff;
            margin-bottom: 10rpx;
        }

        .text {
            width: 100%;
            height: 200rpx;
            background: #000000;
            border: 2rpx solid #333333;
            border-radius: 10rpx;
            box-sizing: border-box;
            color: #fff;
            font-size: 20rpx;
            padding: 24rpx;
        }
    }

    .controller {
        height: 122rpx;
        width: 100%;
        background: #000;
        position: fixed;
        bottom: var(--window-bottom);
        left: 0;
        padding: 0 32rpx;
        box-sizing: border-box;
        z-index: 9;

        .btn {
            width: 100%;
            height: 78rpx;
            border-radius: 39rpx;
            color: #080808;
            align-items: flex-end;
            margin: 20rpx auto;

            .btn-text {
                font-size: 30rpx;
                font-weight: 700;
                line-height: 78rpx;
            }

            .btn-price {
                font-weight: 500;
                font-size: 18rpx;
                line-height: 60rpx;
                letter-spacing: 2.8rpx;
            }
        }
    }
}
</style>
